from django.shortcuts import render
from rest_framework import mixins,status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from goods.models import GoodsGroup, GoodsBanner, Goods, Collect, Detail
from goods.permissions import CollectPermissions
from goods.serializers import GoodsSerializer, GoodsGroupSerializer, GoodsBannerSerializer, CollectSerializer, \
    DetailSerializer
from user.permissions import UserPermissions

# Create your views here.
"""
商品前台接口
1、商城首页
    商品分类
    商品海报
    推荐商品列表
2、点击某个商品
    展示商品的详情信息
3、分类获取商品列表
    支持分类获取（过滤参数）
    
4、收藏商品

"""
class IndexView(APIView):
    def get(self,request):
        """商城首页接口"""
        #序列化如果有图片字段，返回数据需要补全完整图片域名，需要在序列化传入请求对象
    #1、获取商品所有的分类信息
        group=GoodsGroup.objects.filter(status=True)
        group_ser=GoodsGroupSerializer(group,many=True,context={'request':request})
    #2、获取商品的海报
        banner=GoodsBanner.objects.filter(status=True)
        banner_ser=GoodsBannerSerializer(banner,many=True,context={'request':request})
    #3、获取推荐商品
        goods=Goods.objects.filter(recommend=True)
        goods_ser=GoodsSerializer(goods,many=True,context={'request':request})
    #4、返回
        result=dict(
            group=group_ser.data,
            banner=banner_ser.data,
            goods=goods_ser.data
        )
        return Response(result)


##商品视图集
class GoodsView(ReadOnlyModelViewSet):
    queryset = Goods.objects.filter(is_on=True)
    serializer_class = GoodsSerializer
    #实现通过商品分类，和是否推荐进行过滤
    filterset_fields=('group','recommend')
    ordering_fields=('sales','price','id')
    #获取商品详情
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        #获取对应商品详情
        # print(instance)
        detail=Detail.objects.get(goods=instance)
        detail_ser=DetailSerializer(detail)
        result=serializer.data
        result['detail']=detail_ser.data
        return Response(result)

class CollectView(mixins.CreateModelMixin,
                  mixins.DestroyModelMixin,
                  GenericViewSet):
    """
    收藏商品视图集
    收藏  post
    和取消收藏 delete
    ，收藏列表 list
    """
    queryset = Collect.objects.all()
    serializer_class = CollectSerializer
    # 添加权限认证  仅登录访问
    permission_classes = [IsAuthenticated,CollectPermissions]
    def create(self, request, *args, **kwargs):
        """收藏商品"""
        #获取请求参数
        user=request.user
        params_user_id=request.data.get('user')
        #校验请求参数中的用户id为当前登录的用户
        if user.id != params_user_id:
            # print(user,user.id,params_user_id)
            return Response({'error':'没有操作其他用户的权限'})
        #调用继承过来的方法进行创建
        return super().create(request, *args, **kwargs)
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset=queryset.filter(user=request.user)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

#商品分类视图
class GoodsGroupView(mixins.ListModelMixin,
                           GenericViewSet):
    """商品分类"""
    queryset = GoodsGroup.objects.filter(status=True)
    serializer_class = GoodsGroupSerializer




















